package com.godfrey.utils;

import com.godfrey.pojo.Content;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

/**
 * description : 解析网页
 *
 * @author godfrey
 * @since 2020-07-13
 */
@Component
public class HtmlParesUtil {
    public List<Content> paresJd(String keyword) throws IOException {
        String url = "https://search.jd.com/Search?keyword=" + keyword;
        Document document = Jsoup.parse(new URL(url), 30000);
        Element element = document.getElementById("J_goodsList");
        Elements elements = element.getElementsByTag("li");

        List<Content> goodsList = new ArrayList<>();

        for (Element el : elements) {
            String title = el.getElementsByClass("p-name").eq(0).text();
            String price = el.getElementsByClass("p-price").eq(0).text();
            String img = el.getElementsByTag("img").eq(0).attr("src");

            Content content = new Content(title, price, img);
            goodsList.add(content);
        }
        return goodsList;
    }
}
